package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public PageInfo query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Role> list = roleMapper.selectForList(qo);
        return new PageInfo(list);
    }

    @Override
    public void save(Role role, Long[] permissionIds) {
        // 除了往 role 插入角色数据
        roleMapper.insert(role);
        // 还要往中间表 role_permission 中插入关系数据
        if(permissionIds != null){
            for (Long permissionId : permissionIds) {
                roleMapper.insertRelation(role.getId(), permissionId);

            }
        }
    }

    @Override
    public void update(Role role, Long[] permissionIds) {
        roleMapper.updateByPrimaryKey(role);

        // 先从中间表 role_permission 表中删除旧有关系数据
        roleMapper.deleteRelation(role.getId());

        // 在往 中间表 role_permission 表中插入新的关系数据
        if(permissionIds != null){
            for (Long permissionId : permissionIds) {
                roleMapper.insertRelation(role.getId(), permissionId);

            }
        }
    }

    @Override
    public void delete(Long id) {
        // 先从中间表 role_permission 表中删除旧有关系数据
        roleMapper.deleteRelation(id); // 从表
        roleMapper.deleteByPrimaryKey(id); // 主表
    }

    @Override
    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> list() {
        return roleMapper.selectAll();
    }

    @Override
    public List<String> selectAllRoles() {

        return roleMapper.selectAllRoles();
    }

    @Override
    public List<String> queryRolesByEmployeeId(Long id) {
        return roleMapper.queryRolesByEmployeeId(id);
    }

}
